package com.ruoyi.web.controller.wechat;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.vo.WxContentEntity;
import com.ruoyi.system.service.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 *微信小程序接口
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/wechat")
public class WechatController extends BaseController
{
    @Autowired
    private ISysCardService sysCardService;
    @Autowired
    private ISysWxUserService sysWxUserService;
    @Autowired
    private ISysContentService sysContentService;
    @Autowired
    private ISysVipRulesService sysVipRulesService;
    @Autowired
    private ISysNoticeServiceService sysNoticeServiceService;
    @Autowired
    private ISysConfigService configService;//用于动态获取小程序加盟商信息
    @Autowired
    private ISysAboutmeService sysAboutmeService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysNeedpullDataService sysNeedpullDataService;
    /**
     * 获取分类列表
     */
    @GetMapping(value = {"/{ownerid}/classList", "/classList"})
    public Map<String, Object> getClassList(HttpServletResponse response, @PathVariable(required = false) String ownerid) throws IOException
    {
        return new HashMap<>();
    }

    /**
     *
     * @param wxUserEntity
     * @return
     * @throws Exception
     */
    @PostMapping(value = {"/{ownerid}/login", "/login"})
    public AjaxResult login(@RequestBody WxUserEntity wxUserEntity, @PathVariable(required = false) String ownerid) throws  Exception {
        //判断请求的openid是否存在 如果存在  则返回登录信息，否则重新插入  并返回登录信息
        if (wxUserEntity == null || wxUserEntity.getCode() == null || wxUserEntity.getCode().isEmpty()) {
            throw new Exception("wxopenid不可为空");
        }
        String appidCacheKey = "";
        if (StringUtils.isEmpty(ownerid)) {//系统用户
            appidCacheKey = "sys_appid_1";
        } else {
            appidCacheKey = "sys_appid_" + ownerid;
        }
        //缓存获取
        /**
         * 格式为
         * { "LOGIN_URL":"https://api.weixin.qq.com/sns/jscode2session",
         * "APP_ID":"wx807b78a4b0f68c5c",
         * "APP_SECRET":"1676a03e65c35ce42356cb2c677224b9"  }
         */
        String LOGIN_URL = "";
        // 填写上你的AppID，如何获取AppID自行百度，这步骤很简单
        String APP_ID = "";
        // 填写上你的AppSecret，如何获取AppSecret自行百度，这步骤很简单
        String APP_SECRET = "";
        if (!StringUtils.isEmpty(wxUserEntity.getAppid())
        ) {
            appidCacheKey = "sys_appid_" + wxUserEntity.getAppid();//小程序  app密钥需要保存在后台--非蓝海随记 项目  密钥规则为sys_appid_+appkey
        }
        String cacheString = configService.selectConfigByKey(appidCacheKey);
          if (StringUtils.isEmpty(cacheString)) {
                return AjaxResult.error("没有维护appid,请联系管理员！");
            }
            JSONObject jsonObject = JSONObject.parseObject(cacheString);
            // 微信小程序登录校验请求地址
            LOGIN_URL = (String) jsonObject.get("LOGIN_URL");
            // 填写上你的AppID，如何获取AppID自行百度，这步骤很简单
            APP_ID = (String) jsonObject.get("APP_ID");
            // 填写上你的AppSecret，如何获取AppSecret自行百度，这步骤很简单
            APP_SECRET = (String) jsonObject.get("APP_SECRET");
        String code = wxUserEntity.getCode().trim();
        String url = LOGIN_URL + "?appid=" + APP_ID + "&secret=" + APP_SECRET + "&grant_type=authorization_code&js_code=" + code;
        HttpClient client = HttpClients.createDefault(); // 创建默认http连接
        HttpGet getRequest = new HttpGet(url);// 创建一个post请求
        List<SysWxUser> wxuserList = null;
        SysWxUser wxuser = null;
        LoginDTO loginDTO = null;
        try {
            // 用http连接去执行get请求并且获得http响应
            HttpResponse response = client.execute(getRequest);
            // 从response中取到响实体
            HttpEntity entity = response.getEntity();
            // 把响应实体转成文本
            String html = EntityUtils.toString(entity);
            loginDTO = JSON.parseObject(html, LoginDTO.class);
            if (null == loginDTO.getErrcode()) {

            } else {
                return AjaxResult.error("用户微信登录失败，请联系管理员！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("用户微信登录失败，请联系管理员！");
        }
        SysWxUser querySysWxUser = new SysWxUser();
        querySysWxUser.setWxopenid(loginDTO.getOpenid());
        if (!StringUtils.isEmpty(ownerid)) {
            querySysWxUser.setWxopenid(ownerid);
        } else {
            querySysWxUser.setOwnerid("1");
        }

        //查询该用户是否存在，不存在则新建
        wxuserList = sysWxUserService.selectSysWxUserList(querySysWxUser);
        if (wxuserList == null || wxuserList.size() == 0) {
            wxuser = new SysWxUser();
            Long date = System.currentTimeMillis();
            String username = "用户" + Long.toHexString(date);
            wxuser.setWxname(username);
            wxuser.setWxopenid(loginDTO.getOpenid());
            wxuser.setLevel(UserType.PTHY);
            if (sysWxUserService.insertSysWxUser(wxuser) == 0) {
                return AjaxResult.error("注册用户失败，请联系管理员！");
            }
        } else {
            wxuser = wxuserList.get(0);
        }
        Map data = new HashMap();
        data.put("wxid", loginDTO.getOpenid());
        data.put("usertype", wxuser.getLevel());
        //获取小程序logo
        SysUser sysUser = userService.selectUserById(Long.parseLong(querySysWxUser.getOwnerid()));
        if (sysUser != null && sysUser.getAvatar() != null) {
            data.put("headpic", sysUser.getAvatar());
        }
        if (wxuser.getLevel().equals(UserType.NKHY) || wxuser.getLevel().equals(UserType.ZSHY)) {
            //创建Calendar实例
            Calendar cal = Calendar.getInstance();
            cal.setTime(wxuser.getStarttime());   //设置当前时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            data.put("starttime", format.format(cal.getTime()));
            cal.setTime(wxuser.getEndtime());   //
            data.put("endtime", format.format(cal.getTime()));
        }
        data.put("username", wxuser.getWxname());
        return AjaxResult.success(data);
    }
    /**
     *
     * @param cardEntity
     * @return
     * @throws Exception
     */
    @PostMapping(value = {"/{ownerid}/updateCardInfo", "/updateCardInfo"})
    public AjaxResult updateUserCardInfo(@RequestBody WxCardEntity cardEntity, @PathVariable(required = false) String ownerid) throws  Exception
    {
        //判断请求的openid是否存在 如果存在  则返回登录信息，否则重新插入  并返回登录信息
        if (cardEntity==null||cardEntity.getWxid()==null||cardEntity.getWxid().isEmpty()){
            return AjaxResult.error("卡密激活wxopenid不可为空");
        }
        if ( cardEntity.getCardno()==null||cardEntity.getCardno().isEmpty()){
            return AjaxResult.error("卡密激活cardno不可为空");
        }

        String cardno =cardEntity.getCardno().trim();
        SysWxUser querySysWxUser=new SysWxUser();
        SysCard querySysCard=new SysCard();
        querySysCard.setCardNo(cardno);
        querySysWxUser.setWxopenid(cardEntity.getWxid());
        if (!StringUtils.isEmpty(ownerid)){
            querySysWxUser.setOwnerid(ownerid);
            querySysCard.setOwnerid(ownerid);
        }else {
            querySysWxUser.setOwnerid("1");
            querySysCard.setOwnerid("1");
        }
        //查询该用户是否存在，不存在则新建
     List<SysWxUser>   wxUserList= sysWxUserService.selectSysWxUserList(querySysWxUser);
        if (wxUserList==null||wxUserList.size()==0){
         return AjaxResult.error("该用户不存在，请联系管理员！");
        }
        List<SysCard>   sysCardList=sysCardService.selectSysCardList(querySysCard);
        if (sysCardList==null||sysCardList.size()==0){
            return AjaxResult.error("该卡密不存在或已失效，请联系管理员！");
        }
        SysWxUser wxUser=wxUserList.get(0);
        SysCard sysCard=sysCardList.get(0);
        //将卡密更新为不可用状态-已使用   并绑定卡密
        sysCard.setStatus(1);
        sysCardService.updateSysCard(sysCard);
        wxUser.setCardId(sysCard.getCardId());
        wxUser.setLevel(sysCard.getCardType());
        wxUser.setStarttime(sysCard.getStarttime());
        wxUser.setEndtime(sysCard.getEndtime());
        sysWxUserService.updateSysWxUser(wxUser);
        Map data=new HashMap();
        data.put("wxid",wxUser.getWxopenid());
        data.put("usertype",wxUser.getLevel());
        if (wxUser.getLevel().equals(UserType.NKHY)||wxUser.getLevel().equals(UserType.ZSHY)){
            //创建Calendar实例
            Calendar cal = Calendar.getInstance();
            cal.setTime(wxUser.getStarttime());   //设置当前时间
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            data.put("starttime",format.format(cal.getTime()));
            cal.setTime(wxUser.getEndtime());   //
            data.put("endtime",format.format(cal.getTime()));
        }
        data.put("username",wxUser.getWxname());
        return  AjaxResult.success(data);
    }

    /**
     * 获取商品详情
     */
    @GetMapping(value = {"/{ownerid}/articleDetail", "/articleDetail"})
    public AjaxResult getArticleDetail(Long contentid  , @PathVariable(required = false) String ownerid) throws IOException
    {
        SysContent sysContent= sysContentService.selectSysContentByContentid(contentid);
        Map<String, Object> dd= new HashMap<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        dd.put("noticeContent",sysContent.getContent());
        dd.put("creatDate",format.format(sysContent.getCreatedate()) );
        dd.put("title",sysContent.getTitle() );
        dd.put("type",sysContent.getContentType() );
        dd.put("level",sysContent.getLevel() );
        dd.put("contentPath",sysContent.getContentPath() );
        dd.put("contentPic",sysContent.getContentPic() );//获取图片

        return  AjaxResult.success(dd);
    }
    /**
     * 初始化数据，将数据存储至表中
     */
    @PostMapping(value = {"/initNeedPullData" })
    public AjaxResult initNeedPullData(@RequestBody List<NeedPullDataBean> needPullDataBeanList) throws IOException
    {
        int count=0;//记录  数据是否已经存在
        int beforeDatecount=0;
        List<NeedInputBean> needInputBeanList=new ArrayList<>();
        for (int i=0;i<needPullDataBeanList.size();i++){
            NeedPullDataBean needPullDataBean=needPullDataBeanList.get(i);
             if (!(sysContentService.checkResourceIsExist(needPullDataBean.getResourceId()))) {
                 NeedInputBean needInputBean=new NeedInputBean();
                 needInputBean.setResourceId(needPullDataBean.getResourceId());
                 needInputBean.setShowPutTime(needPullDataBean.getShowPutTime());
                needInputBeanList.add(needInputBean);
            }else {
                 count++;
             }

            // 获取当前日期
            LocalDate today = LocalDate.now();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

            // 使用format方法将Date对象转换为字符串
            String formattedDate = formatter.format(needPullDataBean.getShowPutTime());

            // 给定的日期
            LocalDate givenDate = LocalDate.parse(formattedDate); // 替换为你要检查的日期

            // 计算给定日期与当前日期之间的天数差
            long daysBetween = ChronoUnit.DAYS.between(today, givenDate);
            System.out.println("=======时间"+formattedDate);
            System.out.println("=======时间差"+daysBetween);
            // 判断是否在40天内
            if (Math.abs(daysBetween) <= 80) {

            } else {
                beforeDatecount++;
            }

        }
        if (needInputBeanList.size()>0){
            sysContentService.inputResource(needInputBeanList);
        }
        Map<String, Object> dd= new HashMap<>();
        int biaozhun=0;
        String msg="false";//  false表示停止  true表示继续
       if (needInputBeanList.size()<5){
         //hamoreflag 1  表示停止  0表示还可以拉取
       } else  {
         if (count<4){
             msg="true";
         }
       }
       if (msg.equals("true")&&beforeDatecount>3){
           msg="false";
       }

        return  AjaxResult.success(msg,dd);
    }
    /**
     * 初始化数据，将数据存储至表中
     */
    @GetMapping(value = {"/getNeedPullData" })
    public TableDataInfo getNeedPullData() throws IOException
    {
        startPage();
        List<SysNeedpullData> list = sysNeedpullDataService.selectSysNeedpullDataListByCustom();
        return getDataTable(list);
    }
    /**
     * 新增内容维护
     */
    @PostMapping("/add")
    public AjaxResult add(@RequestBody SysContent sysContent)
    {
        //此处添加方法  为定时任务拉取资源的，原资源id暂时使用再SysContent 的queryParam字段上
           //将sys_needpull_data状态改为1   拉取完成
        String resourceId=sysContent.getQueryParam();
        sysContentService.updateNeedPullToSucess(resourceId);
        sysContent.setQueryParam("");//临时字段用完后还原
        return toAjax(sysContentService.insertSysContent(sysContent));
    }
    /**
     *

     * @param unionid  //对应数据库版本
     * @param version--对应小程序版本，当当前版本大于数据库版本时候，为测试待发布版本
     * @return
     */
    @GetMapping(value = {"/unionlist/{unionid}/{version}"})
    public AjaxResult unionlist( @PathVariable(required = true) String unionid, @PathVariable(required = true) String version)
    {
        if ((!TextUtils.isEmpty(unionid))&&(!TextUtils.isEmpty(version))){


            return AjaxResult.success("true",sysContentService.unionlist(unionid,version));

        }

        return AjaxResult.error();


    }
    @DeleteMapping("/refreshCache")
    public AjaxResult refreshCache()
    {
        sysContentService.resetConfigCache();
        return success();
    }
    /**
     *
     * @param wxContentEntity
     * @param ownerid
     * @param versionTag--只用于免费分享小程序审核时使用，审核期间，对应sys_content表中 versionTag相同
     * @return
     */
    @GetMapping(value = {"/{ownerid}/list", "/list", "/list/{versionTag}"})
    public TableDataInfo list(WxContentEntity wxContentEntity, @PathVariable(required = false) String ownerid, @PathVariable(required = false) String versionTag)
    {

        boolean issimi=false;
        //判断是什么资源  如果是私密资源，则查询私密资源
        String queryTitle=wxContentEntity.getQueryTitle();
        if(queryTitle!=null&&!queryTitle.isEmpty()&&queryTitle.startsWith("tag:")){
            //查询的是加密资源
              queryTitle=queryTitle.replaceFirst("tag:","");
              wxContentEntity.setQueryParam(queryTitle);
              issimi=true;
        }
        if (!StringUtils.isEmpty(versionTag)){
            wxContentEntity.setVersionTag(versionTag);
        }
        startPage();
        List<SysContent> list = sysContentService.selectSysContentListByWx(wxContentEntity);
        TableDataInfo dataInfo=getDataTable(list);
        if (issimi){
            dataInfo.setCode(2002);//2002表示请求结果是私密资源
        }
        return dataInfo;
    }
    /**
     *
     * @param wxContentEntity
     * @param ownerid
     * @param versionTag--只用于免费分享小程序审核时使用，审核期间，对应sys_content表中 versionTag相同--小程序  审核专用该接口
     * @return
     */
    @GetMapping(value = { "/cszylist"})
    public TableDataInfo cszylist(WxContentEntity wxContentEntity, @PathVariable(required = false) String ownerid, @PathVariable(required = false) String versionTag)
    {

        boolean issimi=false;
        //判断是什么资源  如果是私密资源，则查询私密资源
        String queryTitle=wxContentEntity.getQueryTitle();

        startPage();
        List<SysContent> list = sysContentService.selectSysContentListByWxcszy(wxContentEntity);
        TableDataInfo dataInfo=getDataTable(list);
        if (issimi){
            dataInfo.setCode(2002);//2002表示请求结果是私密资源
        }
        return dataInfo;
    }
    @GetMapping(value = {"/{ownerid}/carrules", "/carrules"})
    public  AjaxResult carrules(@PathVariable(required = false) String ownerid)
    {
        if (StringUtils.isNotEmpty(ownerid)){
            ownerid="1";
        }
        List<SysVipRules> sysVipRulesList=  sysVipRulesService.selectVipRulesLeast(ownerid);
        if (sysVipRulesList!=null&&sysVipRulesList.size()>0){
            SysVipRules sysVipRules=sysVipRulesList.get(0);
            Map data=new HashMap();
            data.put("detail",sysVipRules.getContent());
            return AjaxResult.success(data);

        }else {
            return  AjaxResult.error("没有数据");
        }
    }
    @GetMapping(value = {"/{ownerid}/noticeAndServer", "/noticeAndServer"})
    public  AjaxResult noticeAndServer( @PathVariable(required = false) String ownerid)
    {
        SysNoticeService sysNoticeService=new SysNoticeService();
        sysNoticeService.setStatus(0);
        if (!StringUtils.isEmpty(ownerid)){
            sysNoticeService.setOwnerid(ownerid);
        }else {
            sysNoticeService.setOwnerid("1");
        }
        List<SysNoticeService> sysNoticeServiceList=  sysNoticeServiceService.selectSysNoticeServiceList(sysNoticeService);
        if (sysNoticeServiceList!=null&&sysNoticeServiceList.size()>0){
            SysNoticeService sysVipRules=sysNoticeServiceList.get(0);
            Map data=new HashMap();
            data.put("notice",sysVipRules.getContent());
            data.put("serverpic",sysVipRules.getServerPic());
            return AjaxResult.success(data);
        }else {
            return  AjaxResult.error("没有数据");
        }
    }

    /**
     *生成卡密
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping(value = {"/{ownerid}/creatCartNo", "/creatCartNo"})
    public AjaxResult creatCartNo(@RequestBody WxCreatCardEntity wxCreatCardEntity, @PathVariable(required = false) String ownerid) throws  Exception
    {
        //判断请求的openid是否存在 如果存在  则返回登录信息，否则重新插入  并返回登录信息
        if (wxCreatCardEntity==null||wxCreatCardEntity.getWxid()==null||wxCreatCardEntity.getWxid().isEmpty()){
            return AjaxResult.error("卡密生成wxopenid不可为空");
        }
        if ( wxCreatCardEntity.getCartype()==null||wxCreatCardEntity.getCartype().isEmpty()){
            return  AjaxResult.error("卡密激活类型不可为空");
        }

        String cartype =wxCreatCardEntity.getCartype().trim();
//        SysWxUser wxUser=null;
        SysWxUser querySysWxUser=new SysWxUser();
        querySysWxUser.setWxopenid(wxCreatCardEntity.getWxid());
        if (!StringUtils.isEmpty(ownerid)){
            querySysWxUser.setWxopenid(ownerid);
        }else {
            querySysWxUser.setOwnerid("1");
        }
        //查询该用户是否存在，不存在则新建
      List<SysWxUser>  wxUserList= sysWxUserService.selectSysWxUserList(querySysWxUser);
        if (wxUserList==null||wxUserList.size()==0){
            return AjaxResult.error("生成卡密该用户不存在，请联系管理员！");
        }
        SysWxUser wxUser=wxUserList.get(0);
        if (!wxUser.getLevel().equals(UserType.GLY)){
            return AjaxResult.error("你没有生成卡密权限,请联系管理员！");
        }
        if (cartype.equals(UserType.NKHY)||cartype.equals(UserType.ZSHY)){
        }else {
            return AjaxResult.error("生成卡密类型错误，目前只支持年卡-终身会员，请联系管理员！");
        }
        String carno = sysCardService.createSysCardNo(ownerid,cartype,wxUser.getWxuserid()+"");
      //插入成功，返回卡密
        Map data=new HashMap();
        data.put("cardNo",carno);
        return  AjaxResult.success(data);
    }

    /**
     * 获取商品详情
     */
    @GetMapping(value = {"/{ownerid}/aboutme", "/aboutme"})
    public AjaxResult aboutme( @PathVariable(required = false) String ownerid) throws IOException
    {
        SysAboutme sysAboutme=new SysAboutme();
        if (!StringUtils.isEmpty(ownerid)){
            sysAboutme.setOwnerid(ownerid);
        }else {
            sysAboutme.setOwnerid("1");
        }
        sysAboutme.setStatus(0);
      List<SysAboutme> sysAboutmeList= sysAboutmeService.selectSysAboutmeList(sysAboutme);
      if (sysAboutmeList!=null&&sysAboutmeList.size()>0){
          Map<String, Object> dd= new HashMap<>();
          dd.put("aboutmeContent",sysAboutmeList.get(0).getContent());
          return  AjaxResult.success(dd);
      }else {
          return  AjaxResult.error("暂无关于信息!");
      }



    }
}
